﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Sector7.Framework.Core;
using Sector7.Medical.STOM.Windows;
using Sector7.Framework.Enums;
using Sector7.Framework.Utility;
using System.ComponentModel;
using Sector7.Medical.Windows;
using Sector7.Medical.Biz;
using Sector7.Medical.Consts;
using Sector7.Medical.Utility;
using Sector7.Medical.EntityType;
using Sector7.Medical.Controls;

namespace Sector7.Medical.STOM.Controls
{
    /// <summary>
    /// AddPurchasesBillControl.xaml 的交互逻辑
    /// </summary>
    public partial class AddPurchasesBillControl : AddModeControlBase
    {
        #region Accessor
        /// <summary>
        /// 获取或设置单据信息
        /// </summary>
        public M7_PurchasesBill Bill
        {
            get { return m_entity as M7_PurchasesBill; }
            set { m_entity = value; }
        }
        #endregion

        #region Public functions
        #endregion

        #region Private functions
        protected override void InitializeForCreating()
        {
            Bill = new M7_PurchasesBill();
            Bill.Items = new List<M7_PurchasesBillItem>();

            base.InitializeForCreating();
        }

        protected override bool CheckData()
        {
            m_errors.Clear();

            Bill.OperatorId = txbOperator.Text;
            if (string.IsNullOrWhiteSpace(Bill.OperatorId))
            {
                m_errors.Add("录入人员", "不能为空");
            }
            Bill.CheckerId = txbChecker.Text;
            if (string.IsNullOrWhiteSpace(Bill.CheckerId))
            {
                m_errors.Add("校核人员", "不能为空");
            }
            Bill.BuyerId = txbBuyer.Text;
            if (string.IsNullOrWhiteSpace(Bill.BuyerId))
            {
                m_errors.Add("采购人员", "不能为空");
            }
            Bill.BookKeeperId = txbBookKeeper.Text;
            if (string.IsNullOrWhiteSpace(Bill.BookKeeperId))
            {
                m_errors.Add("会计", "不能为空");
            }
            Bill.StoreKeeperId = txbStoreKeeper.Text;
            if (string.IsNullOrWhiteSpace(Bill.StoreKeeperId))
            {
                m_errors.Add("库管", "不能为空");
            }
            Bill.PayAmount = Convert.ToDecimal(txbPayAmount.Text);
            if (Bill.Items.Count == 0)
            {
                m_errors.Add("采购单项","不能为空！");
            }            

            return base.CheckData();
        }

        protected override void AddData()
        {
            Bill.BillId = m_billNo;
            Bill.DeptId = Convert.ToInt32(cbbStore.SelectedValue);
            Bill.VendorId = Convert.ToInt32(cbbVendor.SelectedValue);
            Bill.BillDate = (DateTime)datePicker.SelectedDate;
            Bill.Remarks = txbRemarks.Text;
            Bill.PaymentType = Convert.ToInt32((cbbPaymentType.SelectedItem as ComboBoxItem).Tag);

            Agent_STOS.AddPurchasesBill(Bill);

            base.AddData();
        }

        private void AddDrugItemControl()
        {
            var drugItemControl = new DrugItemControlForPUR();
            drugItemControl.Height = 30;
            drugItemControl.ClickAdd += new EventHandler(DrugItemControl_ClickAdd);
            drugItemControl.ClickDelete += new EventHandler(DrugItemControl_ClickDelete);
            drugItemControl.ItemUpdated += new EventHandler(DrugItemControl_DrugItemUpdated);

            stpMain.Children.Add(drugItemControl);
        }

        private void RemoveDrugItemControl(DrugItemControlForPUR drugItemControl)
        {
            var item = Bill.Items.Find(delegate(M7_PurchasesBillItem __item)
            {
                return __item.ItemId == drugItemControl.ItemId;
            });
            Bill.Items.Remove(item);

            stpMain.Children.Remove(drugItemControl);

            if (stpMain.Children.Count == 0)
            {
                stpMain.Children.Add(txbPrompt);
            }
        }

        void DrugItemControl_ClickDelete(object sender, EventArgs e)
        {
            RemoveDrugItemControl(sender as DrugItemControlForPUR);
        }

        void DrugItemControl_DrugItemUpdated(object sender, EventArgs e)
        {
            var itemControl = sender as DrugItemControlForPUR;
            var item = itemControl.GetItem(m_billNo);
            if (item != null)
            {
                if (Bill.Items.Find(delegate(M7_PurchasesBillItem __item)
                {
                    if (__item.ItemId == item.ItemId)
                    {
                        __item = item;
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }) == null)
                {
                    Bill.Items.Add(item);
                }

                Bill.BillAmount += item.PurchasesPrice * item.Number;
                txbAmount.Text = Bill.BillAmount.ToString();
            }
        }

        void DrugItemControl_ClickAdd(object sender, EventArgs e)
        {
            var itemControl = sender as DrugItemControlForPUR;
            var item = itemControl.GetItem(m_billNo);
            Bill.Items.Add(item);

            Bill.BillAmount += item.PurchasesPrice * item.Number;
            txbAmount.Text = Bill.BillAmount.ToString();

            AddDrugItemControl();
        }

        private void LoadData()
        {
            ClientUtil.LoadItemsSource(cbbVendor, m_vendorList);
            ClientUtil.LoadItemsSource(cbbStore, m_storeList);
            Bill.BillId = m_billNo;
            txbBillId.Text = Bill.BillId.ToString();
            datePicker.SelectedDate = DateTime.Now;

            Senvironments.ProgressWindow.Visibility = Visibility.Hidden;
        }

        private void txbUser_GotFocus(object sender, RoutedEventArgs e)
        {
            var authWindow = new AuthenticationWindow();
            bool? result = authWindow.ShowDialog();

            if (result == true)
            {
                var txb = sender as TextBox;
                txb.Text = authWindow.UserName;
            }
        }

        private void btnAddVendor_Click(object sender, RoutedEventArgs e)
        {
            var addVendorWindow = new AddVendorWindow();
            addVendorWindow.InitializeWindow(CrudType.Create);
            addVendorWindow.AddSuccess += new EventHandler(AddVendorWindow_AddSuccess);
            addVendorWindow.ShowDialog();
        }

        private void AddVendorWindow_AddSuccess(object sender, EventArgs e)
        {
            var addVendorWindow = sender as AddVendorWindow;
            cbbVendor.Items.Add(addVendorWindow.Vendor);
        }

        private void btnAddStore_Click(object sender, RoutedEventArgs e)
        {

        }

        private void AddModeControlBase_Loaded(object sender, RoutedEventArgs e)
        {
            Senvironments.ProgressWindow.Visibility = Visibility.Visible;

            if (m_crud == CrudType.Unknown)
            {
                InitializeControl(CrudType.Create);
            }

            datePicker.SelectedDate = DateTime.Now;

            var worker = BackgroundWorkerUtil.GetWorker(this);
            worker.DoWork += new DoWorkEventHandler(Worker_DoWork);
            worker.RunWorkerAsync();
        }

        private void Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            if(m_crud == CrudType.Create)
            {
                var billDate = DateTime.Now.ToString("yyyyMMdd");
                var seed = Agent_SYSS.GetBinarySeed(C_M7_TableName.PURCHASES_BILL, C_BillType.PURCHASES_BILL.ToString());
                m_billNo = Convert.ToInt64(PrimaryKeyUtil.GetPrimaryKey(
                    C_M7_TableName.PURCHASES_BILL,
                    billDate,
                    C_BillType.PURCHASES_BILL,
                    seed));
            }
            m_vendorList = Agent_INFS.GetVendorList();
            m_storeList = Agent_INFS.GetDepartmentListByComflags(C_DepartmentFlags.PHARMACY | C_DepartmentFlags.STORAGE);

            this.Dispatcher.BeginInvoke(new DelegateWithNothing(LoadData));
        }

        private void lblStart_MouseDown(object sender, MouseButtonEventArgs e)
        {
            stpMain.Children.Clear();

            AddDrugItemControl();
        }

        private void lblStart_MouseEnter(object sender, MouseEventArgs e)
        {
            lblStart.Cursor = Cursors.Hand;
        }

        private void lblStart_MouseLeave(object sender, MouseEventArgs e)
        {
            lblStart.Cursor = Cursors.Arrow;
        }
        #endregion

        #region Structure
        public AddPurchasesBillControl()
        {
            InitializeComponent();
        }
        #endregion

        #region Inner members
        private long m_billNo;
        private List<M7_Vendor> m_vendorList = null;
        private List<M7_Department> m_storeList = null;
        #endregion
    }
}
